<?php

namespace App\Helper;


use zgldh\QiniuStorage\QiniuStorage;

class ImageHelper
{
    const IMAGE_TYPE_COVER      = 1;   // 微信消息
    const IMAGE_TYPE_AVATAR     = 2;   // 头像
    const IMAGE_TYPE_PHOTO      = 3;   // 宣传照
    const IMAGE_TYPE_POSTER     = 4;   // 海报
    const IMAGE_TYPE_IMAGE      = 5;   // 通用图片
    const IMAGE_TYPE_THUMBNAIL  = 6;   // 缩略图
    const IMAGE_TYPE_HOME       = 7;   // 医生主页图片

    const GRAVITY_NORTH_WEST    = 1;   // 左上角
    const GRAVITY_NORTH         = 2;   // 正上方
    const GRAVITY_NORTH_EAST    = 3;   // 右上角
    const GRAVITY_WEST          = 4;   // 正左方
    const GRAVITY_CENTER        = 5;   // 正中间
    const GRAVITY_EAST          = 6;   // 正右方
    const GRAVITY_SOUTH_WEST    = 7;   // 左下角
    const GRAVITY_SOUTH         = 8;   // 正下方
    const GRAVITY_SOUTH_EAST    = 9;   // 右下角

    const IMAGE_PREFIX = 'http://ptd-image.tcmlive.com/';

    /**
     * Name: getTeamImage
     * Desc: 取得团队图片
     *
     * Author: wangxj
     * Date: 2018/12/3
     *
     * @param     $image
     * @param int $type
     *
     * @return string
     */
    public static function getTeamImage($image, $type = self::IMAGE_TYPE_IMAGE)
    {
        if ($type == self::IMAGE_TYPE_COVER)
        {
            $defaultImage = 'http://ptd-image.tcmlive.com/team_introduction2.jpg';
        }
        else
        {
            $defaultImage = 'http://ptd-image.tcmlive.com/team_img.png';
        }

        return self::getCommonImage($image, $defaultImage);
    }

    /**
     * Name: getDoctorImage
     * Desc: 取得医生图片
     *
     * Author: wangxj
     * Date: 2018/12/3
     *
     * @param     $image
     * @param int $type
     *
     * @return string
     */
    public static function getDoctorImage($image, $type = self::IMAGE_TYPE_AVATAR)
    {
        switch ($type)
        {
            case self::IMAGE_TYPE_COVER:
                $defaultImage = 'http://ptd-image.tcmlive.com/doctor_cover.png';
                break;
            case self::IMAGE_TYPE_AVATAR:
                $defaultImage = 'http://ptd-image.tcmlive.com/doctor_avatar.png';
                break;
            case self::IMAGE_TYPE_PHOTO:
                $defaultImage = 'http://ptd-image.tcmlive.com/doctor_img.png';
                break;
            case self::IMAGE_TYPE_POSTER:
                $defaultImage = 'http://ptd-image.tcmlive.com/doctor_img.png';
                break;
            default:
                $defaultImage = 'http://ptd-image.tcmlive.com/doctor_img.png';

        }

        // todo getCommonImage() 接口默认拼接了图片瘦身参数，七牛云的 imageInfo 接口，不能接其他参数，否则会报错。
        // $dstImage =  self::getCommonImage($image, $defaultImage);
        $dstImage =  self::getInitImage($image, $defaultImage);

        if ($type == self::IMAGE_TYPE_AVATAR)
        {
            $info = HTTPHelper::request('get',$dstImage . '?imageInfo');
            if ($info)
            {
                $min = min($info['width'], $info['height']);
                if ($min > 0)
                {
                    $imageMogr2 = "imageMogr2/crop/{$min}x{$min}";
                    // if (strpos($dstImage, '?') === false)
                    // {
                    //     $dstImage .= "?" . $imageMogr2;
                    // }
                    // else
                    // {
                    //     $dstImage .= "&" . $imageMogr2;
                    // }

                    $dstImage = self::addImageParameter($dstImage, $imageMogr2);
                }
            }
        }

        return $dstImage;
    }

    /**
     * Name: getUserImage
     * Desc: 取得用户图片
     *
     * Author: wangxj
     * Date: 2018/12/3
     *
     * @param     $image
     * @param int $type
     *
     * @return string
     */
    public static function getUserImage($image, $type = self::IMAGE_TYPE_IMAGE)
    {
        $defaultImage = 'http://ptd-image.tcmlive.com/user.png';

        return self::getCommonImage($image, $defaultImage);
    }

    /**
     * Name: getArticleImage
     * Desc: 取得文章图片
     *
     * Author: wangxj
     * Date: 2018/12/3
     *
     * @param     $image
     * @param int $type
     *
     * @return string
     */
    public static function getArticleImage($image, $type = self::IMAGE_TYPE_IMAGE)
    {
        if ($type == self::IMAGE_TYPE_THUMBNAIL)
        {
            $defaultImage = 'http://ptd-image.tcmlive.com/article_thumbnail.png';
        }
        else
        {
            $defaultImage = 'http://ptd-image.tcmlive.com/team_img.png';
        }

        return self::getCommonImage($image, $defaultImage);
    }

    /**
     * Name: getCommonImage
     * Desc: 图片共通处理
     *
     * Author: wangxj
     * Date: 2018/11/30
     *
     * @param $src     : 源图片
     * @param $default : 缺省图片
     * @param $prefix  : 路径前缀
     */
    private static function getCommonImage($srcImage, $default, $prefix = '')
    {
        $dstImage = $srcImage;

        if (empty($dstImage))
        {
            $dstImage = $default;
        }
        elseif (substr($dstImage, 0, 5) !== 'http:' && substr($dstImage, 0, 6) !== 'https:')
        {
            if (empty($prefix))
            {
                $prefix = 'http://ptd-image.tcmlive.com/';
            }

            $dstImage = $prefix . $dstImage;
        }

        // // 图片瘦身 imageslim
        // if (strpos($dstImage, '?') === false)
        // {
        //     $dstImage .= '?imageslim';
        // }
        // else
        // {
        //     $dstImage = '&imageslim';
        // }

        $dstImage = self::addImageParameter($dstImage, "imageslim");

        return $dstImage;
    }

    private static function getInitImage($srcImage, $default, $prefix = '')
    {
        $dstImage = $srcImage;

        if (empty($dstImage))
        {
            $dstImage = $default;
        }
        elseif (substr($dstImage, 0, 5) !== 'http:' && substr($dstImage, 0, 6) !== 'https:')
        {
            if (empty($prefix))
            {
                $prefix = 'http://ptd-image.tcmlive.com/';
            }

            $dstImage = $prefix . $dstImage;
        }

        return $dstImage;
    }

    /**
     * Name: getGravityImage
     * Desc: 通过图片的某个部分截取图片
     *
     * Author: zhangjing
     * Date: 2019/1/31
     *
     * @param     $image
     * @param     $type
     * @param     $width
     * @param     $height
     *
     * @return    string
     */
    public static function getGravityImage($image, $type = self::GRAVITY_NORTH, $width = 750, $height = 750)
    {
        $dstImage = $image;

        if (empty($dstImage))
        {
            $dstImage = 'http://ptd-image.tcmlive.com/doctor_avatar.png';
        }
        elseif (substr($dstImage, 0, 5) !== 'http:' && substr($dstImage, 0, 6) !== 'https:')
        {

            $prefix = 'http://ptd-image.tcmlive.com/';

            $dstImage = $prefix . $dstImage;
        }

        $qiNiuUrl = "imageMogr2/gravity/";

        switch ($type)
        {
            case self::GRAVITY_NORTH_WEST:
                $qiNiuUrl .= 'NorthWest';
                break;
            case self::GRAVITY_NORTH:
                $qiNiuUrl .= 'North';
                break;
            case self::GRAVITY_NORTH_EAST:
                $qiNiuUrl .= 'NorthEast';
                break;
            case self::GRAVITY_WEST:
                $qiNiuUrl .= 'West';
                break;
            case self::GRAVITY_CENTER:
                $qiNiuUrl .= 'Center';
                break;
            case self::GRAVITY_EAST:
                $qiNiuUrl .= 'East';
                break;
            case self::GRAVITY_SOUTH_WEST:
                $qiNiuUrl .= 'SouthWest';
                break;
            case self::GRAVITY_SOUTH:
                $qiNiuUrl .= 'South';
                break;
            case self::GRAVITY_SOUTH_EAST:
                $qiNiuUrl .= 'SouthEast';
                break;
        }

        $qiNiuUrl .= "/crop/".$width."x".$height;

        // if (strpos($dstImage, '?') === false)
        // {
        //     $dstImage .= '?'.$qiNiuUrl;
        // }
        // else
        // {
        //     $dstImage = '&'.$qiNiuUrl;
        // }

        $dstImage = self::addImageParameter($dstImage, $qiNiuUrl);

        return $dstImage;
    }

    /**
     * Name: getFixedSizeImage
     * Desc: 取得固定大小图片
     *
     * Author: zhangjing
     * Date: 2019/1/10
     *
     * @param     $image
     * @param     $type
     *
     * @return    string
     */
    public static function getFixedSizeImage($image, $type = self::IMAGE_TYPE_HOME)
    {
        $dstImage = $image;

        if (empty($dstImage))
        {
            $dstImage = 'http://ptd-image.tcmlive.com/doctor_avatar.png';
        }
        else
        {
            $dstImage = self::getImageFullAddress($dstImage);
        }

        if($type == self::IMAGE_TYPE_HOME)
        {
            // $dstImage .= '&imageMogr2/thumbnail/750x1100!';
            $dstImage = self::addImageParameter($dstImage, "imageMogr2/thumbnail/750x1100!");
        }

        // // 图片瘦身 imageslim
        // if (strpos($dstImage, '?') === false)
        // {
        //     $dstImage .= '?imageslim';
        // }
        // else
        // {
        //     $dstImage = '&imageslim';
        // }

        $dstImage = self::addImageParameter($dstImage, "imageslim");


        return $dstImage;
    }
    /**
     * 生成图片名字
     * @param   $path   照片的路径
     */
    public static function getImgNewName($path)
    {
        $pathInfo=pathinfo($path);
        #生成字符串
        $str = uniqid(mt_rand(),1);
        $name=date('ymd').'_'.sha1($str).'.'.$pathInfo['extension'];
        return $name;
    }

    /**
     * [handleImgSize 处理图片，添加参数，压缩和缩略]
     * @param  [type] $path [图片路径]
     * @return [type]       [description]
     */
    public static function handleImgSize($path)
    {
        if(strpos($path, '?') !== false)
        {
            $path = substr($path, '0',strpos($path, '?'));
        }

        //$newPath = $path.'?imageView2/2/w/200/h/200';
        $newPath = self::addImageParameter($path, "imageView2/2/w/200/h/200");
        return $newPath;
    }

    /**
     * 根据指定宽高比，截取图片
     * @param $image
     * @param int $ratioW 宽的比例
     * @param int $ratioH 高的比例
     * @return string
     */
    public static function ratioCutImage($image, $ratioW = 1, $ratioH = 1)
    {
        if (empty(trim($image)))
        {
            $avatar = 'http://ptd-image.tcmlive.com/doctor_avatar.png';
        }
        else
        {
            $avatar = self::getImageFullAddress($image);
        }

        $ratioW = intval($ratioW);
        $ratioH = intval($ratioH);

        $info  = getimagesize($avatar);

        // 计算需要截取的比例值
        $ratioValue = round($ratioW / $ratioH, 4);

        $width = $info[0];
        $height = $info[1];
        // 计算图片实际宽高的比例值
        $imageRatioValue = round($width / $height, 4);

        // 如果图片比例值 大于 截取比例值 * 计算截取比例值 ：25w / 22h = 1.14
        //* 计算图片比例值 ：（1000w / 800h = 1.25）图A    |    （1000w / 900h = 1.11）图B
        //* 如果图片比例值  > 截取比例值（图A）
        //    * 1.25  > 1.14 那么高度不变，计算宽度： 800 * 25 / 22 = 909
        //    * 实际截取大小：909w 800h
        //* 如果图片比例值 < 截取比例值 （图B）
        //    * 1.11  < 1.14 那么宽度不变，计算高度： 1000 * 22 / 25 = 880
        //    * 实际截取大小：1000w 880h

        if ($imageRatioValue > $ratioValue) {
            $width = $height * $ratioW / $ratioH;
        } else if ($imageRatioValue < $ratioValue) {
            $height = $width * $ratioH / $ratioW;
        }

        // $avatar .= '?imageMogr2/gravity/North/crop/'.$width.'x'.$height;
        $avatar = self::addImageParameter($avatar, 'imageMogr2/gravity/North/crop/'.$width.'x'.$height);

        return $avatar;
    }

    public static function getUserRandomAvatar()
    {
        $avatar = 'http://static.tcmmooc.com/assets/img/avatar/avatar200/' . rand(1, 12). '.png';

        return $avatar;
    }

    /**
     * 获取图片全地址
     * @param $image
     * @return string
     */
    public static function getImageFullAddress($image)
    {
        if (substr($image, 0, 5) !== 'http:' && substr($image, 0, 6) !== 'https:')
        {
            $image = self::IMAGE_PREFIX . $image;
        }

        return $image;
    }

    public static function getImagePreviewAddress($image)
    {
        if (substr($image, 0, 5) !== 'http:' && substr($image, 0, 6) !== 'https:')
        {
            #图片截取
            $disk = QiniuStorage::disk('qiniu');
            // $previewUrl = $disk->privateDownloadUrl($image . '?imageView2/1/w/200/h/200/interlace/1');
            $previewUrl = $disk->privateDownloadUrl($image);
            $previewUrl = self::addImageParameter($previewUrl, "imageView2/1/w/200/h/200/interlace/1");
        }
        else
        {
            // $previewUrl = $image . "?imageMogr2/gravity/Center/crop/500x500";
            $previewUrl = self::addImageParameter($image, "imageMogr2/gravity/Center/crop/500x500");
        }

        return $previewUrl;
    }

    public static function addImageParameter($url, $parameter)
    {
        $parameter = ltrim($parameter,'/');
        $parameter = ltrim($parameter,'?');
        $parameter = ltrim($parameter,'&');
        $parArray = explode('/', $parameter);

         if (count($parArray) > 0)
        {
            $mode = $parArray[0];

            $imageModes = ['imageslim', 'imageMogr2', 'imageView2'];
            $isCanAdd = true;
            if (in_array($mode, $imageModes))
            {
                // 查找所有已使用的mode
                foreach ($imageModes as $imageMode)
                {
                    $pos1 = strpos($url, "?{$imageMode}");
                    $pos2 = strpos($url, "&{$imageMode}");

                    if ($pos1 !== false || $pos2 !== false)
                    {
                        $isCanAdd = false;
                        break;
                    }
                }
            }

            if ($isCanAdd)
            {
                // 图片瘦身 imageslim
                if (strpos($url, '?') === false)
                {
                    $url .= "?{$parameter}";
                }
                else
                {
                    $url .= "&{$parameter}";
                }
            }
        }

        return $url;
    }
}
